
export function createUrl(data: Uint8Array | ArrayBuffer) {
    return URL.createObjectURL(new Blob([data]));
}

export function formatPrice(price: number) {
    return (price / 100).toFixed(2)
}

export function formatDate(timestamp: number) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const date2 = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const sec = date.getSeconds();
    return `${year}-${month}-${date2} ${hour}:${minute}:${sec}`;
}


export function formatSize(size: number) {
    if (size < 1024) {
        return `${size}Byte`;
    } else if (size < (1024 * 1024)) {
        return `${(size / 1024).toFixed(2)}KB`;
    } else if (size < (1024 * 1024 * 1024)) {
        return `${(size / 1024 / 1024).toFixed(2)}MB`;
    } else {
        return `${size}Byte`;
    }
}

export function nullDefault<T>(v: T | null, def: T) {
    if (v == null) {
        return def;
    }
    return v;
}

export function formatPlayTime(n: number) {
    const h = Math.floor(n / 3600);
    const m = Math.floor((n % 3600) / 60);
    const s = n % 60;
    return `${h}:${m}:${s}`;
}

export function parsePlayTime(date: Date) {
    const h = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    return h * 3600 + m * 60 + s;
}

export function saveFile(name: string, content: Uint8Array) {
    const blob = new Blob([content]);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = name;
    link.click();
    URL.revokeObjectURL(link.href);
}

export interface WsConn {
    socket: WebSocket,
    event: Event,
}

export function connectWebsocket(url: string, cb: (data: Uint8Array) => void) {
    return new Promise<WsConn>((reolve, reject) => {
        const ws = new WebSocket(url);
        ws.binaryType = 'arraybuffer';
        ws.onopen = (event) => {
            reolve({
                socket: ws,
                event
            });
        };
        ws.onerror = (event) => {
            reject(event)
        };
        ws.onmessage = (event) => {
            cb(new Uint8Array(event.data));
        }
        ws.onclose = (event) => {
            console.error('socket close', event);
        }
    });
}

export function parseNumber(s: string) {
    const value = parseInt(s);
    if (isNaN(value)) {
        throw '请输入数字';
    }
    return value;
}

export function createImageUrl(body: Uint8Array) {
    const url = URL.createObjectURL(new Blob([body]));
    return url;
}

